package com.zy.project.system.user.entity.base;

import com.alibaba.fastjson.annotation.JSONField;
import com.zy.core.common.constant.enums.StatusEnum;
import com.zy.core.common.constant.system.SysConstant;
import com.zy.core.data.jpa.support.entity.BaseEntity;
import com.zy.project.system.role.entity.SystemRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;

import javax.persistence.*;
import java.util.Date;
import java.util.Set;

/**
 * Package: core.entity.base
 * <p>
 * Description： TODO
 * <p>
 * Author: zhangyu
 * <p>
 * Date: Created in 2018-9-5 21:38
 * <p>
 * Copyright: Copyright (c) 2018
 * <p>
 * Version: 0.0.1
 * <p>
 * Modified By:
 */

@Getter
@Setter
@MappedSuperclass
public class BaseSystemUser extends BaseEntity {
    /**
     *主键id
     */
    @Id
    @GenericGenerator(name ="jpa-uuid", strategy = "uuid")
    @GeneratedValue(generator = "jpa-uuid")
    @Column(name = "id")
    private String id;

    /**
     * 登录名
     */
    @Column(name = "username")
    private String username;

    /**
     * 真实名称
     */
    @Column(name = "realName")
    private String realName;

    /**
     * 登录密码
     */
    @Column(name = "password")
    private String password;

    /**
     * 盐加密
     */
    @Column(name = "salt")
    private String salt;

    /**
     * 最后登陆IP
     */
    @Column(name = "login_ip")
    private String loginIp;

    /**
     * 最后登陆时间
     */
    @Column(name = "login_date")
    private Date loginDate;

    /**
     * 账号状态参考 {@link StatusEnum}
     * @type 告诉hibernate使用自己的类型转换器
     */
    @Type(type = SysConstant.DB_CONVERT_NAME)
    @Column(name = "status")
    private StatusEnum status;

    /**
     * 描述
     */
    @Column(name = "description")
    private String description;

    /**
     * 用户与角色的关系
     * 注意这里cascade不能少,否则一方保存多方时候会报瞬时态引用错误
     */
    @ManyToMany(fetch= FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(name="system_user_role",
            joinColumns={@JoinColumn(name="user_id",referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="role_id",referencedColumnName="id")})
    @JSONField(serialize=false)
    private Set<SystemRole> roles;

    /**
     * 获取盐的证书(username + salt)
     * @return
     */
    public String getCredentialsSalt(){
        return getUsername() + getSalt();
    }
}
